package com.jdk.mode.struct;

import com.jdk.mode.build.SafeSingleton;

import java.util.HashMap;
import java.util.Map;
import java.util.logging.Handler;

/**
 * @author jukg
 * @date 2023/08/25 17:02
 * @description 享元模式-共享一个元组件
 */
public class Flyweight {

    public static void main(String[] args) {
        Shape shape = ShapeFactory.getShape(1);
        shape.draw();
        shape = ShapeFactory.getShape(2);
        shape.draw();
        shape = ShapeFactory.getShape(1);
        shape.draw();
    }
}

interface Shape{

    void draw();
}

class Circle implements Shape{
    private Integer x;

    public Circle(Integer x) {
        this.x = x;
    }

    @Override
    public void draw() {
        System.out.println("generate a " + x + "circle");
    }
}

class ShapeFactory{

    private static Map<Integer, Shape> map = new HashMap<>();

    public static Shape getShape(Integer x){
        Shape shape = map.get(x);
        if(shape == null){
            shape = new Circle(x);
            map.put(x, shape);
        }
        return shape;
    }

}
